 //index.js
//获取应用实例
const app = getApp()
var network = require("../../utils/NetWorkUtils.js")
var utils=require("../../utils/appUtils.js")
var prizeId='';
var investopenid='';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //控制弹窗是否显示
    isshowDialog:false,
    advertisementBanner:'',
    share_time:0, //分享次数
    invite_get_gold:0,//邀请领金币
    sign_get_gold:0,//签到领金币
    my_gold:0,//我的金币
    free_time:0,//今日答题机会
    commodityLength:0,//金币免费兑换的商品有几个
    commodityList: [],//金币免费兑换的商品列表数据
    inviteLength: 0,//邀请的商品有几个
    inviteList: [],//邀请专区的商品数据
    attentionAnim:"",//签到动画
    signed:0,//是否签到0,
    jump_object:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  this.investopenid= 0;
    if (options&&options.prizeId){
      prizeId = options.prizeId;
    }
    if (options&&options.openid){
      investopenid = options.openid
    }

    if (options && options.jumpPage&&options.id){
      var jumpPage = options.jumpPage;
      var id = options.id;
      if (jumpPage =="inviteDetail"){
        wx.navigateTo({
          url: '/pages/InviteDetail/inviteDetail?id='+id,
        })
      }
    }
    console.log(options)
    var that=this;
      // 检查是否授权
      wx.getSetting({
        success(e){
          console.log(e)
          //如果已经授权
          if (e.authSetting['scope.userInfo']){
            //授权隐藏弹窗
            that.setData({
              isshowDialog:true
            })
          }else{
             //未授权显示弹窗
            that.setData({
              isshowDialog: false
            })
          }
        }
      })

    try {
      const value = wx.getStorageSync('userInfo')
      console.log(value)
      if (value) {
        app.globalData.openId = value.openId;
        app.globalData.userNmae = value.nickName;
        app.globalData.avatarUrl = value.headImage;
        app.globalData.token = value.token
      }
    } catch (e) {
      // Do something when catch error
    }

   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var attentionAnim = wx.createAnimation({
      duration: 2000,
      timingFunction: 'ease',
      delay: 0
    })
    //设置循环动画
    this.attentionAnim = attentionAnim
    var next = true;
    setInterval(function () {
      if (next) {
        //根据需求实现相应的动画
        this.attentionAnim.translateY(10).step()
        next = !next;
      } else {
        this.attentionAnim.translateY(-10).step()
        next = !next;
      }
      this.setData({
        //导出动画到指定控件animation属性
        attentionAnim: attentionAnim.export()
      })
    }.bind(this), 800)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that=this
      // 检查授权是否过期
      wx.checkSession({
        success:function(e){
          that.setData({
            isshowDialog: true
          })
        },
        fail:function(e){
          that.setData({
            isshowDialog: false
          })
        }
      })

      that.requestIndex();
    that.requestCommodity();
    that.requestButtomBanner();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    wx.showShareMenu({
      withShareTicket: true
    })
    //如果是通过转发答题按钮分享的需要加一次答题机会
      console.log(options.from)
    if (options.from == 'button') {
      return {
        title: '我正在答题赚钱，免费兑换商品，快来和我一起抢！',
        path: 'pages/index/index?openid=' + app.globalData.openId,
        imageUrl: '../../images/share_pic.jpg',
      }
    } else {
      return {
        title: '我正在答题赚钱，免费兑换商品，快来和我一起抢！',
        path: 'pages/index/index',
        imageUrl: '../../images/share_pic.jpg',
      }
    }
  },
  answerQuestions:function(){

    if (this.data.free_time <=0)
    {

        wx.showToast({
          title: this.data.share_time == 0 ?'您没有答题机会啦！快去邀请好友赚金币吧~': '您没有答题机会啦！快转发到群补充机会~',
          icon: 'none',
        })
        return;
    }
    wx.navigateTo({
      url: '/pages/answer/index',
    })
  },

  _signShareButtonBeTouch:function(){
    this.alertSignInview = this.selectComponent("#alertSignInview");
    this.alertSignInview.hideAlertView();
  },
  //转发到群,答题机会+1按钮
  shareButton:function(){

    var that = this;
    var requestData = { }
    network.requestHttp("m=api&c=Index&a=share", requestData, function (res) {
      that.free_time = res.data.data.free_time;
      console.log(res);
      console.log(that.free_time);
      if (!res.data.data.free_time){
          return;
      }
      that.setData({
        free_time: res.data.data.free_time
      })
    }) 
  },

  signBtn:function(){
    var that=this;
    var dataparm={}
    network.requestHttp("m=api&c=Index&a=sign", dataparm,function(res){
      console.log(res)
      if(res.data.state==1){
        that.alertSignInview = that.selectComponent("#alertSignInview");
        that.alertSignInview.showAlertView();
        that.setData({
          signed:1,
          my_gold: res.data.data
        })
      }
    })
  },
  
  //赚金币按钮
  earnCoin:function(){
    console.log(this.data.invite_get_gold)
    console.log(this.data.sign_get_gold)
    
    var invite_get_gold = this.data.invite_get_gold;
    var sign_get_gold = this.data.sign_get_gold
    wx.navigateTo({
      url: '/pages/earnCoin/earnCoin?invite_get_gold=' + invite_get_gold + "&signGetGold=" + sign_get_gold,
    })
   },
//金币兑换全部商品按钮
  browseAllCommodity:function(){
    wx.navigateTo({
      url: '/pages/exchangeCoin/index',
    })
},
//邀请专区全部商品按钮
  allInvite:function(){
    wx.navigateTo({
      url: '/pages/InvitationCone/invitationZone',
    })
  },
//邀请免费兑换
  invite_exchange:function(e){
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      url: '/pages/InviteDetail/inviteDetail?id='+e.currentTarget.dataset.id,
    })
  },
  //金币兑换详情
  exchangeDetail:function(e){
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      url: '/pages/productDetail/index?id='+e.currentTarget.dataset.id,
    })
  },

//请求底部banner图片
requestButtomBanner:function(){
  var that=this;
  var requestData = {position:1}
  network.requestHttp("m=api&c=Index&a=banner", requestData,function(res){
    console.log(res)
    that.setData({
      advertisementBanner:res.data.data.pic,
      jump_object: res.data.data
    })
  }) 
},

//请求首页信息接口
requestIndex:function(){
  var that = this
  var requestData = { 
    // openid: app.globalData.openId,
    // logincode:app.globalData.token
   }
  network.requestHttp("m=api&c=Index&a=index", requestData,function(res){
    console.log(res);
    console.log(res.data.data);
    if (res.data.data){
      that.setData({
        //邀请获得金币
        invite_get_gold: res.data.data.spread_coin,
        //签到获得金币
        sign_get_gold: res.data.data.sign_coin,
        //我的金币
        my_gold: res.data.data.coin,
        //今日答题次数
        free_time: res.data.data.free_time,
        //是否签到1签了,0没签
        signed: res.data.data.signed,
        //分享次数
        share_time: res.data.data.share_time
      })
    }
  })
},

  //请求首页商品兑换接口
  requestCommodity:function(){
    var that=this;
    var dataparam = {type:1}
    network.requestHttp("m=api&c=Index&a=change",dataparam,function(data){
      that.setData({
        commodityLength: data.data.data.prize1.length,
        commodityList: data.data.data.prize1,
        inviteLength: data.data.data.prize2.length,
        inviteList: data.data.data.prize2,
      })
      console.log(data)
    })
  },
  //底部banner跳转
  banner_jump(){
    var dataParam={
      id:1
    }
    network.requestHttp("m=api&c=Index&a=clicked", dataParam,function(res){
  
    })
    var that=this;
  

    if (that.data.jump_object.jump=='2')
    {
      wx.navigateToMiniProgram({
        appId: that.data.jump_object.appid,
        path: that.data.jump_object.path
      })
    }else
    {
      wx.navigateTo({
        url: '../webView/indexWebView?bannerUrl=' + that.data.jump_object.jump_url
      })
    }
    

    
  },
  //跳转玩转攻略
  jump_strategy() {
    wx.navigateTo({
      url: '../webView/indexWebView?bannerUrl=https://www.jianxiongxcx.com/api/web/contact/id/2'
    })
  },
  //点击允许授权后的操作
  onGotUserInfo(e){
    let userInfo = e.detail.userInfo;
    var that=this;
    console.log(e)
    if (e.detail.userInfo) {
      //调用公共授权登录方法
      network.resetLogin(investopenid,prizeId,userInfo,function(){
         that.setData({
              isshowDialog: true
            })
        setTimeout(function () {
          that.onLoad();
          that.onShow();
        }, 1000)                
      })
        // wx.login({
        //   success:function(res){
        //     console.log(res);
        //     if(res.code){
        //       //参数
        //       let dataParams={
        //         code:res.code
        //       }
        //       console.log(res.code)
        //       //授权后请求获取openid接口
        //       network.requestHttp('m=api&c=Index&a=getopenid', dataParams,
        //         function (res) {
        //           console.log(res);
        //           that.setData({
        //             isshowDialog: true
        //           })
        //           //登录成功设置全局公共参数变量
        //           app.globalData.openId = res.data.data.openid;
        //           app.globalData.userNmae = userInfo. nickName;
        //           app.globalData.avatarUrl = userInfo.avatarUrl;
        //           app.globalData.token = utils.md5(res.data.data.openid + res.data.data.timeout + 'lsj123')
        //           //保存用户信息到本地
        //           var saveUserInfo = {};
        //           saveUserInfo['openId'] = res.data.data.openid;
        //           saveUserInfo['headImage'] = userInfo.avatarUrl;
        //           saveUserInfo['nickName'] = userInfo.nickName;
        //           saveUserInfo['token'] = utils.md5(res.data.data.openid + res.data.data.timeout + 'lsj123')
        //           console.log(res.data.data.openid);
        //           wx.setStorageSync('userInfo', saveUserInfo);
        //           //参数
        //           var dataParams = {
        //             // openid: res.data.data.openid,
        //             headimgurl: userInfo.avatarUrl,
        //             nickname: userInfo.nickName,
        //             // logincode:utils.md5(res.data.data.openid + res.data.data.timeout+'lsj123')
        //           }
        //           //请求登录接口
        //           network.requestHttp('m=api&c=Index&a=login', dataParams,
        //             function (res) {
        //               //请求成功设置全部变量
        //               that.onLoad();
        //             })
        //         })
        //     }
        //   }
        // })
          } else {
            wx.showModal({
              title: '警告',
              content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
              showCancel: false,
              confirmText: '返回授权',
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击了“返回授权”')
                }
              }
            })
          }
  }
})